package com.zdj.data.net;

import android.content.Context;

import com.zdj.data.base.BaseDatas;
import com.zdj.data.entity.HomePageData;
import com.zdj.data.entity.Login;
import com.zdj.data.response.TestResponse;

import retrofit2.adapter.rxjava.Result;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class NetWorks extends RetrofitUtils {

    private static Context mContext;

    //创建实现接口调用
    protected static NetService service ;

    public static void init(Context context){
        mContext = context;
        service = getRetrofit(mContext).create(NetService.class);
    }


    //设缓存有效期为1天
    protected static final long CACHE_STALE_SEC = 60 * 60 * 24 * 1;
    //查询缓存的Cache-Control设置，使用缓存
    protected static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_SEC;
    //查询网络的Cache-Control设置。不使用缓存
    protected static final String CACHE_CONTROL_NETWORK = "max-age=0";



    private interface NetService {

        @GET(value = "searchSchool")
        Observable<Result<TestResponse>> loadSchoolList(@Query("search_key") String tip);

        @GET(value = "login.json")
        Observable<Result<Login>> login(@Query("username") String username, @Query("password") String password);

        @GET(value = "getHomePageData")
        Observable<Result<BaseDatas<HomePageData>>> getHomePageData();

    }

    public static void loadSchoolList(String tip,Subscriber subscriber){
        setSubscribe(service.loadSchoolList(tip),subscriber);
    }

    public static void login(String username,String password,Subscriber subscriber){
        setSubscribe(service.login(username,password),subscriber);
    }

    public static void getHomePageData(Subscriber subscriber) {
        setSubscribe(service.getHomePageData(),subscriber);
    }


    public static <T> void setSubscribe(Observable<T> observable, Subscriber<T> subscriber) {
        observable.subscribeOn(Schedulers.io()) //子线程访问网络
                .observeOn(AndroidSchedulers.mainThread())//回调到主线程
                .subscribe(subscriber);
    }

}